"use strict";
const path = require('path');
const electron = require("electron");
const { screen } = require('electron');
const { app, BrowserWindow, ipcMain } = require("electron");
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib';
let supportWindow, supportBaseUrl, supportParams;
const isDevelopment = process.env.NODE_ENV !== "production";

function createSupportWindow() {
  const { width, height } = electron.screen.getPrimaryDisplay().bounds;
  console.log("Creating support window", width, height);
  supportWindow = new BrowserWindow({
    width,
    height,
    show: true,
    backgroundColor: '#1e1e1e',
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true,
      webSecurity: false,
    },
    resizable: true,
    transparent: false,
    fullscreen: false,
    frame: true,
  });

  supportWindow.loadURL(`${supportBaseUrl}?${supportParams}`);
  // supportWindow.loadURL('http://localhost:8080/loading.html'); // 解决白屏bug

  // supportWindow.webContents.once("did-finish-load", () => {
  //   supportWindow.webContents.executeJavaScript(`
  //     let loginFrame = document.createElement("iframe");
  //     loginFrame.src = "${supportBaseUrl}?${supportParams}";
  //     loginFrame.style = "width: 100%; height: 100%; border: none; position: absolute; top: 0; left: 0;";
  //     loginFrame.id = "loginFrame";
  //     document.body.appendChild(loginFrame);

  //     loginFrame.onload = function() {
  //       loginFrame.style.display = "block";  // 显示 iframe
  //       document.body.style.background = "#1e1e1e";
  //     };
  //   `);
  // });

  supportWindow.on("closed", () => {
    supportWindow = null;
  });

  supportWindow.setMenuBarVisibility(false);

  supportWindow.maximize();

  supportWindow.on("maximize", () => {
  });

  supportWindow.on("unmaximize", () => {
    const newWidth = 1600;
    const newHeight = 800;

    const x = Math.round((width - newWidth) / 2);
    const y = Math.round((height - newHeight) / 2);

    supportWindow.setBounds({ width: newWidth, height: newHeight, x, y });
  });

  supportWindow.webContents.once('did-finish-load', () => {
    supportWindow.show();
  });
}

ipcMain.on('broadcast-window-close', () => {
  if (supportWindow) {
    supportWindow.close();
  }
});

function listensupportWindowEvents() {
  ipcMain.on('open-support-window', (event, args) => {
    const { currentUrl, loginUrl } = args;
    if (!supportWindow) {
      supportBaseUrl = currentUrl;
      supportParams = loginUrl;
      createSupportWindow();
    } else {
      if (supportWindow.isMinimized()) {
        supportWindow.restore();
      }
      supportWindow.focus();
    }
  });
}

export { listensupportWindowEvents };